<template>
    <div class="service_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button v-auth="'IMPORT_CUSTOMER'" type="primary" @click="Input">录入客户</el-button>
            </template>
        </ZwTable>
    </div>
    <ImportCustomer ref="ImportCustomerRef" :batch-import-type="3" @save="reloadTable" />
    <ZWDrawer ref="DetailedRef" @confirm="handleconfirm">
        <detailed :id="cus_import_id" :key="cus_import_id" />
    </ZWDrawer>
    <ZWDepart ref="DepartRef" @submit="getDepart" />
    <ZWDepartImport ref="ZWDepartImportRef" @submit="getDepartImport" />
</template>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import detailed from './components/detailed.vue';
import ZWDrawer from '@/components/ZWDrawer.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import ZWDepartImport from '@/components/ZWDepart.vue';
import ImportCustomer from '../list/components/ImportCustomer.vue';
import { ElMessage } from 'element-plus';
import { getSetionId, defaultTime } from '@/utils/utils';
import { getCustomerList, distributionFile } from '@/api/customer';
import { ref, reactive, computed } from 'vue';
import { deepCopy } from '@/utils/helper';
import { parabolaAnimation } from '@/utils/parabola';

const defaultParams = {
    import_role: [],
    time: []
};

const tableRef = ref<any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '导入者',
            name: 'import_role',
            value: [],
            type: 'select',
            placeholder: '请选择创建人',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            collapseTags: true,
            filterable: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '上传时间',
            name: 'time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: defaultTime(),
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    tableRef.value.getTable().clearSelection();

    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        upload_time: v.time && v.time.length > 0 ? v.time[0] + '~' + v.time[1] : ''
    };
};
const reset = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = { ...deepCopy(defaultParams) };
};
// 表格
const tableOption = [
    {
        prop: 'file_name',
        label: 'Excel名称',
        width: 350
    },
    {
        prop: 'import_name',
        label: '导入者',
        width: 120
    },
    {
        prop: 'tag_info',
        label: '客户标签',
        width: 200,
        isTag: true
    },
    {
        prop: 'assign_employees',
        label: '分配员工',
        width: 600,
        render({ row, column, index }) {
            if (row.assign_employees && row.assign_employees.length == 0) return '--';
            if (row.assign_employees && row.assign_employees.length) {
                return (
                    <el-popover placement="top-start" trigger="hover" width="auto">
                        {{
                            reference: () => (
                                <div class="tag_box">
                                    {row.assign_employees.map((item: any, index: number) => {
                                        return (
                                            <>
                                                <div> {item.content}</div>
                                                {item.work_user.map((work: any) => (
                                                    <div key={work.id} style="display: flex; flex-wrap: wrap">
                                                        <div class="tag_box">
                                                            <sapn style="padding: 0 5px">{work.name}</sapn>
                                                            <span class="zw-el-tags">
                                                                {work.work_department.map((department: any) => (
                                                                    <el-tag key={department.id}>
                                                                        {department.name}
                                                                    </el-tag>
                                                                ))}
                                                            </span>
                                                        </div>
                                                    </div>
                                                ))}
                                            </>
                                        );
                                    })}
                                </div>
                            ),
                            default: () => (
                                <el-scrollbar max-height={300}>
                                    {row.assign_employees.map((item: any, index: number) => {
                                        return (
                                            <>
                                                <div> {item.content}</div>
                                                {item.work_user.map((work: any) => (
                                                    <div key={work.id} style="display: flex; flex-wrap: wrap">
                                                        <div class="tag_box">
                                                            <sapn style="padding: 0 5px">{work.name}</sapn>
                                                            <span class="zw-el-tags">
                                                                {work.work_department.map((department: any) => (
                                                                    <el-tag key={department.id}>
                                                                        {department.name}
                                                                    </el-tag>
                                                                ))}
                                                            </span>
                                                        </div>
                                                    </div>
                                                ))}
                                            </>
                                        );
                                    })}
                                </el-scrollbar>
                            )
                        }}
                    </el-popover>
                );
            }
        }
    },
    {
        prop: 'cust_record_num',
        label: '创建客户数/客户总数/记录总数',
        align: 'left',
        width: 280,
        render({ row, column, index }) {
            return row.cust_import_num + '/' + row.cust_import_total_num + '/' + row.cust_record_num;
        }
    },
    {
        prop: 'created_at',
        label: '上传时间',
        minWidth: 180
    },
    {
        prop: 'created_user',
        label: '创建人',
        width: 150
    },
    {
        prop: 'operate',
        label: '操作',
        width: 200,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '客户明细',
                authCode: 'VIEW_CUSTOMER_DETAIL',
                click: (row: any) => {
                    Detailed(row);
                }
            },
            {
                name: '分配员工',
                authCode: 'ASSIGN_STAFF',
                click: (row: any) => {
                    openDepart(row);
                }
            }
        ]
    }
];

const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return getCustomerList;
};
// 刷新表格
const reloadTable = e => {
    parabolaAnimation(e);
    tableRef.value.reload();
};

const cus_import_id = ref('');
const handleconfirm = () => {};

//打开新建选择人
const DepartRef: any = ref(null);
const creators = ref([]); // 创建人options
const openDepart = (val: any) => {
    if (val.cust_import_num == 0) {
        ElMessage.warning('无可分配客户');
        return;
    }
    DepartRef.value.selectedMember = [];
    state.searchParams.import_id = val.id;
    state.searchParams.customer_list = getSetionId('id', val.import_cust);
    DepartRef.value.departVisble = true;
};
// 获取部门成员
const getDepart = async (res: any, isCancel: boolean) => {
    if (isCancel) {
        DepartRef.value.departVisble = false;
        return;
    }
    creators.value = res;
    state.searchParams.work_user_list = getSetionId('id', creators.value);
    DepartRef.value.removeItem([]);
    await distributionFile(state.searchParams);
    ElMessage.success('分配成功');
    reloadTable();
};

// 导入者
const ZWDepartImportRef = ref<any>(null); // 导入者
const openDepartImport = () => {
    ZWDepartImportRef.value.departVisble = true;
};
const getDepartImport = (res: any) => {
    state.searchParams.import_role = getSetionId('id', res);
};

const DetailedRef = ref<any>(null);

const Detailed = (val: any) => {
    DetailedRef.value.width = 1000;
    DetailedRef.value.drawer = true;
    DetailedRef.value.isShow = false;
    DetailedRef.value.title = val.file_name;
    cus_import_id.value = val.id;
    // cus_import_id.value = 10
};

const ImportCustomerRef = ref<any>(null);
const Input = () => {
    setTimeout(() => {
        ImportCustomerRef.value.appDialog.visible = true;
    }, 0);
};
</script>

<style lang="scss" scoped>
.service_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

:deep(.tag_box) {
    max-height: 80px;
}

:global(.form-tags) {
    margin: 0 8px 8px 0;
}
</style>
